<template>
    <view class="participant-page">
        <!-- 搜索栏 -->
        <view class="search-bar">
            <uni-icon name="search" class="search-icon"></uni-icon>
            <input 
                type="text" 
                placeholder="请输入活动名称" 
                v-model="searchValue" 
                class="search-input"
            />
            <button class="search-button" @click="performSearch">搜索</button>
        </view>
        <!-- 分类标签 -->
        <view class="category-tabs">
            <view 
                v-for="tab in tabs" 
                :key="tab.value"
                :class="['tab-item', activeTab === tab.value ? 'tab-active' : 'tab-default']"
                @click="switchTab(tab.value)">
                {{ tab.label }}
            </view>
        </view>
        <!-- 活动列表 -->
        <ActivityList
            :filtered-activities="filteredActivities"
            :is-refreshing="isRefreshing"
            :has-more="hasMore"
            @refresh="onRefresh"
            @load-more="onLoadMore"
            @activity-click="gotoActivityDetail"
        />
    </view>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import ActivityList from '@/components/ActivityList/ActivityList.vue';
import { useActivityDetailStore } from '@/store/modules/activity/activitydetail';
import { useActivityStore } from '@/store/modules/activity/activity';
import useUserStore from '@/store/modules/user';

// 数据状态
const myActivities = ref([]);
const isRefreshing = ref(false);
const hasMore = ref(true);
const searchValue = ref('');
const actualSearchKeyword = ref('');
const activeTab = ref('all');
const activityDetailStore = useActivityDetailStore();
const activityStore = useActivityStore();
const userStore = useUserStore();

//获取用户学号
const stu_id = userStore.name;
console.log("学生学号",stu_id)
console.log(activityStore.activities)
const act_id_list = ref([]);
// 获取活动详细信息,界面加载时候执行
const loadActivityMyDetail = async () => {
  uni.showLoading({ title: "加载中..." });
  
  try {
    // 确保活动数据已加载
    if (!activityStore.activities || activityStore.activities.length === 0) {
      await activityStore.loadActivities();
    }
    
    console.log("所有活动数据:", activityStore.activities);
    
    // 获取用户已录取的活动ID列表
    const response = await activityDetailStore.loadActivityDetailList({
      studentNumber: stu_id,
      status: "已录取"
    });
    
    console.log("已录取活动详情响应:", response);
    
    if (!response || !response.data) {
      console.error("获取已录取活动失败", response);
      myActivities.value = [];
      uni.hideLoading();
      return;
    }
    
    act_id_list.value = response.data.map(item => item.activityId).filter(id => id);
    console.log("已录取活动ID列表:", act_id_list.value);
    
    // 如果没有任何已录取活动，直接返回空数组
    if (!act_id_list.value || act_id_list.value.length === 0) {
      myActivities.value = [];
      uni.hideLoading();
      return;
    }
    
    // 检查活动数据格式
    console.log("活动数据格式检查:", activityStore.activities[0]);
    
    // 直接使用已加载的活动数据进行筛选和格式转换
    const filteredActivities = activityStore.activities.filter(activity => 
      activity && activity.activityId && act_id_list.value.includes(activity.activityId)
    ).map(activity => ({
      activityId: activity.activityId,
      title: activity.activityName || '未命名活动',
      location: activity.activityLocation || '未知地点',
      status: activity.status || '未知状态',
      category: activity.creditType || '未分类',
      participantLimit: activity.participantLimit || 0,
      dateRange: `${activity.activityStart || ''} - ${activity.activityEnd || ''}`,
      activityStart: activity.activityStart, // 添加活动开始时间字段用于排序
      activityEnd: activity.activityEnd // 添加活动结束时间字段
    }));
    
    console.log("筛选后的已录取活动:", filteredActivities);
    
    // 按开始时间降序排序
    const sortedActivities = filteredActivities.sort((a, b) => {
      try {
        // 直接使用活动开始时间进行排序，不再使用split方法
        if (!a.activityStart || !b.activityStart) {
          return 0; // 如果任一活动开始时间为空，保持原顺序
        }
        
        const dateA = new Date(a.activityStart);
        const dateB = new Date(b.activityStart);
        
        // 检查日期是否有效
        if (isNaN(dateA.getTime()) || isNaN(dateB.getTime())) {
          return 0; // 如果日期无效，保持原顺序
        }
        
        return dateB - dateA; // 降序排序，最新的活动在前
      } catch (e) {
        console.error('日期排序错误:', e);
        return 0; // 如果解析失败，保持原顺序
      }
    });
    
    myActivities.value = sortedActivities;
    console.log("最终显示的活动:", myActivities.value);
    
  } catch (error) {
    console.error("加载活动数据出错:", error);
    myActivities.value = [];
  } finally {
    uni.hideLoading();
  }
};


// 分类标签数据
const tabs = [
    { value: 'all', label: '全部' },
    { value: '报名中', label: '报名中' },
    { value: '进行中', label: '进行中' },
    { value: '等待中', label: '等待中' },
    { value: '已结束', label: '已结束' },
    { value: '已补录', label: '已补录' }
];
// 执行搜索
const performSearch = () => {
    actualSearchKeyword.value = searchValue.value;
};

// 筛选活动
const filteredActivities = computed(() => {
    let filtered = myActivities.value;
    
    // 根据标签筛选
    if (activeTab.value !== 'all') {
        const targetStatus = activeTab.value;
        if (targetStatus) {
            filtered = filtered.filter(item => item.status === targetStatus);
        }
    }   
    
    // 根据搜索关键词筛选
    if (actualSearchKeyword.value.trim()) {
        const keyword = actualSearchKeyword.value.toLowerCase();
        filtered = filtered.filter(item => 
            item.title.toLowerCase().includes(keyword) ||
            item.location.toLowerCase().includes(keyword)
        );
    }
    
    return filtered;
});

// 下拉刷新
const onRefresh = async () => {
    isRefreshing.value = true;
    try {
        await loadActivityMyDetail();
    } finally {
        isRefreshing.value = false;
    }
};

// 上拉加载更多
const onLoadMore = () => {
    hasMore.value = false;
};

// 前往活动详情
const gotoActivityDetail = (activityId) => {
    uni.navigateTo({
        url: `/pages_activity/pages/details/index?id=${activityId}`
    });
};
// 切换标签
const switchTab = (tab) => {
    activeTab.value = tab;
};
// 页面加载时获取数据
onMounted(() => {
    loadActivityMyDetail();
});
</script>

<style scoped>
.participant-page {
    min-height: 100vh;
    background: linear-gradient(to bottom, #f8f9ff, #f5f7fa);
}
.page-header {
    background: white;
    padding: 40rpx 30rpx 20rpx;
    text-align: center;
    box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
}

.page-title {
    font-size: 36rpx;
    font-weight: 700;
    color: #2c3e50;
    background: linear-gradient(135deg, #667eea, #764ba2);
    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent;
    background-clip: text;
}

.search-bar {
    display: flex;
    align-items: center;
    margin-bottom: 20rpx;
    background: white;
    border-radius: 30rpx;
    padding: 20rpx;
    box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.05);
}

/* 搜索图标样式 */
.search-icon {
    margin-right: 10rpx;
    color: #999;
    font-size: 32rpx;
}

/* 搜索输入框样式 */
.search-input {
    flex: 1;
    height: 60rpx;
    font-size: 28rpx;
    background: #f5f5f5;
    border-radius: 30rpx;
    padding: 0 20rpx 0 50rpx;
    position: relative;
}

/* 搜索输入框内的放大镜样式 */
.search-input::before {
    content: "🔍";
    position: absolute;
    left: 15rpx;
    top: 50%;
    transform: translateY(-50%);
    font-size: 28rpx;
    color: #999;
}

/* 搜索按钮样式 */
.search-button {
    margin-left: 10rpx;
    padding: 0 30rpx;
    height: 60rpx;
    line-height: 60rpx;
    background: white;
    color: black;
    border-radius: 30rpx;
    font-size: 27rpx;
    font-weight: 500;
    border: none;
    box-shadow: 0 2rpx 8rpx rgba(102, 126, 234, 0.3);
}
/* 分类标签样式 */
.category-tabs {
    display: flex;
    flex-wrap: wrap;
    background: white;
    border-radius: 16rpx;
    padding: 16rpx;
    margin-bottom: 16rpx;
    box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.05);
}

.tab-item {
    padding: 10rpx 18rpx;
    margin: 0 5rpx;
    font-size: 26rpx;
    font-weight: 580;
    transition: color 0.3s ease, transform 0.3s ease;
    color: #000000;
    position: relative;
}

.tab-active {
    color: rgba(0, 122, 255, 100);
    transform: translateY(-2rpx);
}

.tab-active::after {
    content: '';
    position: absolute;
    bottom: 0;
    left: 0;
    width: 100%;
    height: 3rpx;
    background-color: rgba(0, 122, 255, 100);
    animation: slideIn 0.3s ease forwards;
}

@keyframes slideIn {
    from {
        width: 0;
        left: 50%;
    }
    to {
        width: 100%;
        left: 0;
    }
}


</style>